<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cesium 1.134.1 稳定PBR案例</title>
  <script src="https://cesium.com/downloads/cesiumjs/releases/1.134/Build/Cesium/Cesium.js"></script>
  <link href="https://cesium.com/downloads/cesiumjs/releases/1.134/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
  
  <style>
    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    #cesiumContainer {
      width: 100%;
      height: 100%;
    }
    .controls {
      position: absolute;
      top: 20px;
      left: 20px;
      background: rgba(30, 30, 30, 0.9);
      color: white;
      padding: 15px;
      border-radius: 8px;
      z-index: 100;
      max-width: 300px;
    }
    .control-group {
      margin-bottom: 15px;
    }
    input[type="range"] {
      width: 100%;
    }
    button {
      background: #444;
      color: white;
      border: none;
      padding: 6px 12px;
      border-radius: 4px;
      cursor: pointer;
    }
    button.active {
      background: #4CAF50;
    }
  </style>
</head>
<body>
  <div id="cesiumContainer"></div>
  
  <div class="controls">
    <h3>PBR控制器</h3>
    
    <div class="control-group">
      <label>金属度: <span id="metallicValue">0.5</span></label>
      <input type="range" id="metallic" min="0" max="1" step="0.01" value="0.5">
    </div>
    
    <div class="control-group">
      <label>粗糙度: <span id="roughnessValue">0.5</span></label>
      <input type="range" id="roughness" min="0" max="1" step="0.01" value="0.5">
    </div>
    
    <div class="button-group">
      <button id="sphereBtn" class="active">球体</button>
      <button id="cubeBtn">立方体</button>
    </div>
  </div>

  <script>
    const TOKEN =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmMWNhZjBmOS1lZWExLTQyMTMtYmE0NS03NjZjYTg3ZTVhMDYiLCJpZCI6MjE4NTQ3LCJpYXQiOjE3MTY5NDU4NjV9.Anho0I4q39DvWDKTXrzMDmTFwdGn88gHim8RBHrJQmo";

    // 替换为您自己的Cesium令牌
    Cesium.Ion.defaultAccessToken = TOKEN;

    // 初始化Viewer，禁用可能引起冲突的功能
    const viewer = new Cesium.Viewer('cesiumContainer', {
    //   terrainProvider: Cesium.createWorldTerrain(),
      orderIndependentTranslucency: false, // 禁用可能导致渲染问题的功能
      contextOptions: {
        webgl: {
          alpha: false,
          antialias: true
        }
      },
      baseLayerPicker: false,
      timeline: false,
      animation: false,
      infoBox: false
    });

    // 关键修复：使用安全的渲染配置
    viewer.scene.highDynamicRange = false; // 禁用HDR以避免兼容性问题
    viewer.scene.exposure = 1.0;
    viewer.scene.backgroundColor = Cesium.Color.BLACK;

    // 使用Cesium内置天空盒，避免外部资源加载问题
    viewer.scene.skyBox = new Cesium.SkyBox({
      sources: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_px.jpg'),
      sources: {
        positiveX: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_px.jpg'),
        negativeX: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_mx.jpg'),
        positiveY: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_py.jpg'),
        negativeY: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_my.jpg'),
        positiveZ: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_pz.jpg'),
        negativeZ: Cesium.buildModuleUrl('Assets/Textures/SkyBox/tycho2t3_80_mz.jpg')
      }
    });

    // 安全创建PBR材质的方式
    let pbrMaterial;
    try {
      pbrMaterial = Cesium.Material.fromType('PBR', {
        baseColor: new Cesium.Color(0.5, 0.8, 0.9, 1.0),
        metallic: 0.5,
        roughness: 0.5,
        alpha: 1.0
      });
    } catch (e) {
      console.error('创建PBR材质失败，使用 fallback 材质:', e);
      // 提供fallback材质，确保程序不崩溃
      pbrMaterial = Cesium.Material.fromType('Color');
      pbrMaterial.uniforms.color = new Cesium.Color(0.5, 0.8, 0.9, 1.0);
    }

    // 几何体管理 - 使用简单几何体避免复杂计算
    let currentEntity;
    
    function createSphere() {
      return viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 3000),
        ellipsoid: {
          radii: new Cesium.Cartesian3(2000, 2000, 2000),
          material: pbrMaterial
        }
      });
    }
    
    function createCube() {
      return viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 3000),
        box: {
          dimensions: new Cesium.Cartesian3(4000, 4000, 4000),
          material: pbrMaterial
        }
      });
    }
    
    // 初始化场景
    currentEntity = createSphere();
    viewer.zoomTo(currentEntity);

    // 事件监听使用安全的方式
    function safeAddEventListener(elementId, event, handler) {
      const element = document.getElementById(elementId);
      if (element) {
        element.addEventListener(event, handler);
      }
    }
    
    safeAddEventListener('sphereBtn', 'click', () => {
      if (currentEntity) viewer.entities.remove(currentEntity);
      currentEntity = createSphere();
      viewer.zoomTo(currentEntity);
      updateActiveButton('sphereBtn');
    });
    
    safeAddEventListener('cubeBtn', 'click', () => {
      if (currentEntity) viewer.entities.remove(currentEntity);
      currentEntity = createCube();
      viewer.zoomTo(currentEntity);
      updateActiveButton('cubeBtn');
    });
    
    function updateActiveButton(activeId) {
      document.querySelectorAll('button').forEach(btn => {
        btn.classList.remove('active');
      });
      const activeBtn = document.getElementById(activeId);
      if (activeBtn) activeBtn.classList.add('active');
    }
    
    // 材质参数控制 - 添加错误处理
    safeAddEventListener('metallic', 'input', (e) => {
      try {
        const value = parseFloat(e.target.value);
        if (pbrMaterial && pbrMaterial.uniforms) {
          pbrMaterial.uniforms.metallic = value;
          document.getElementById('metallicValue').textContent = value.toFixed(2);
        }
      } catch (err) {
        console.error('更新金属度失败:', err);
      }
    });
    
    safeAddEventListener('roughness', 'input', (e) => {
      try {
        const value = parseFloat(e.target.value);
        if (pbrMaterial && pbrMaterial.uniforms) {
          pbrMaterial.uniforms.roughness = value;
          document.getElementById('roughnessValue').textContent = value.toFixed(2);
        }
      } catch (err) {
        console.error('更新粗糙度失败:', err);
      }
    });
    
    // 配置光源（简化版）
    viewer.scene.light = new Cesium.DirectionalLight({
      direction: new Cesium.Cartesian3(-1, -1, -1),
      intensity: 1.0
    });

    // 错误捕获机制
    window.addEventListener('error', (e) => {
      console.error('全局错误:', e);
      alert('渲染发生错误: ' + e.message);
    });
  </script>
</body>
</html>